import axios from 'axios'
import { urlConfig, env } from './urlConfig.js'
import { MessageBox, Message } from 'element-ui'
import { theRequest } from './auth.js'
import index from '../router/index.js'
import router from '../router/index.js'
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// create an axios instancu
const { token } = theRequest()
if (env === "prod") {
  console.log = function () { }
}
console.log('当前：', urlConfig)
const service = axios.create({
  // baseURL: 'http://192.168.80.110:12201/', // url = base url + request url
  // if(requestBaseUrl == 'outside'){

  // }
  baseURL: urlConfig.httpUrl,
  withCredentials: false, // 表示跨域请求时是否需要使用凭证
  // baseURL: process.env.KERNEL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 200000,// request timeout

})

const apiItem = {
  environmentId: "",
  systemId: 1,
  method: "",
  serviceId: 1,
  url: "/:id/:name/:type"
}

<<<<<<< HEAD
// request interceptor
service.interceptors.request.use(
  async config => {
=======
const logItem ={
  environmentId: "",
  systemId: 1,
  content: "",
  serviceId: 1,
}


// request interceptor
service.interceptors.request.use(
 async config => {
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
    // do something before request is sent
    if (config.requestBaseUrl == 'outside') {
      config.baseURL = urlConfig.b1bUrl
    } else {
      config.baseURL = urlConfig.httpUrl
    }
<<<<<<< HEAD

=======
    // 监控系统接口调用日志
    // apiItem.url = window.location.hash.substr(1)
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
    apiItem.method = config.method
    if(env == 'dev'){
      apiItem.environmentId = 1
    }else if(env == 'test'){
      apiItem.environmentId = 2
    }else if(env == 'prod'){
<<<<<<< HEAD
      apiItem.environmentId = 3
=======
      apiItem.environmentId = 4
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
    }
   await axios.post(urlConfig.b1bUrl + 'api/v1/interfaceCallLog/save',apiItem)


<<<<<<< HEAD
=======


>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
    /* if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    } */

    // 如果有token, 通过请求头携带token
    // const token =localStorage.getItem("token")
    // console.log("判断请求头token", config)
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    // const token = "dweuigfwghfhsgdfjey8873uefhsi"
    // if(token){
    //   config.headers['token'] = token
    // }
    // config.headers['responseType'] = 'arraybuffer'
    if (index.history.current.path.split('/')[3] == 2) {
      config.headers['Extension'] = 'Authorization\'907d64edbed348879e988334c6343deb'
      if (token) {
        config.headers['Authorization'] = 'Bearer ' + token
      }
    } else {
      config.headers['Extension'] = 'Authorization\'8ce368116fc846ec98233ed893e2c185'
    }

    // config.headers['Extension'] = 'Authorization\'907d64edbed348879e988334c6343deb'
    // config.headers['responseType'] = 'blob'
    return config

  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async response => { // 200--299
    // 如果是下载文件，则直接返回二进制数据
    if (response.headers['content-type'] === 'application/octet-stream;charset=UTF-8' || response.headers['content-type'] === 'application/json;charset=utf-8') {
      return response.data;
    } else {
      const res = response.data
      // console.log(res, 'res')
      // if the custom code is not 20000, it is judged as an error.
      if (res.code !== 20000 && res.code !== 200 && res.success !== true) {
        // Message({
        //   message: (typeof res.data === 'string' && res.data) || res.message || 'Error',
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        console.error((typeof res.data === 'string' && res.data) || res.message || 'Error')
        logItem.content = (typeof res.data === 'string' && res.data) || res.message || 'Error';
        if(env == 'dev'){
          apiItem.environmentId = 1
        }else if(env == 'test'){
          apiItem.environmentId = 2
        }else if(env == 'prod'){
          apiItem.environmentId = 4
        }
        await axios.post(urlConfig.b1bUrl + '/api/v1/frontEndLog/page',logItem)

        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }

    }
  },
  error => {
    // console.log('err11111111111', error.response.status) // for debug
    const code = error.response.status || error.response.data.status || 500
    if (index.history.current.path.split('/')[3] == 2) {
      if (code) {
        // console.log(code,'1111111');
        // router.replace({
        //   path: '/'
        // })
      }
    }
    // Message({
    //   message:error.response.data || error.message || error.response.data.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)


export default service
